package org.jeecg.modules.paycenter.channel.bankdocking.utils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SocketClient {
    private Socket socket = null;
    private OutputStream outputStream = null;
    private InputStream inputStream = null;
    public SocketClient(){

    }
    public boolean conn(String url, int port){
        try {
            socket = new Socket(url, port);
            return socket.isConnected();
        }catch (Exception e){
            return false;
        }
    }
    public boolean sendData(String data){
        try {
            socket.setSoTimeout(30000);
            outputStream = socket.getOutputStream();
            outputStream.write(data.getBytes("gbk"));
//            outputStream.flush();
//            socket.shutdownOutput();//关闭输出流
            return true;
        }catch (Exception e){
            this.close();
            return false;
        }
    }
    public String receiveData() throws Exception {
        try {
            inputStream = socket.getInputStream();
            StringBuffer sb = new StringBuffer();
            int len = 0;

            byte[] buf = new byte[1024];
//            int rn = 0;
            while (true) {
                try {
                    len = inputStream.read(buf);
                } catch (Exception e) {
                    throw e;
                }
                if (len == -1) {
                    break;
                }
                String td = new String(buf, 0, len, "gbk");
                sb.append(td);
            }
            return sb.toString();
        }catch (Exception e){
            throw e;
        }finally {
            close();
        }
    }

    public void close(){
        try {
            if (outputStream != null) {
                outputStream.close();
                outputStream = null;
            }
            if (inputStream != null) {
                inputStream.close();
                inputStream = null;
            }
            if (socket != null) {
                socket.close();
                socket = null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) throws IOException {
//        Socket socket = new Socket("127.0.0.1", 15999);
//        System.out.println(socket.isConnected());
//    }
}
